<template>
  <view class="order-confirm-page">


    <!-- 安装地点选择 -->
    <view class="location-section" @click="selectLocation">
      <view class="location-header">
        <text class="location-label">计划安装位置</text>
      </view>
      <view class="location-content">
        <text class="location-address">喜民大街家园路万科子山1栋地下A233车位</text>
        <image class="location-edit" src="/static/images/common/ico_edit.png" />
      </view>
    </view>

    <!-- 商品信息 -->
    <!-- 上边框线 -->
    <view class="border-line"></view>
    
    <view class="product-section">
      <view class="product-info">
        <image class="product-image" src="https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/images/activity_pile/pile.png" />
        <view class="product-details">
          <view class="product-price">
            <text class="current-price">¥{{ activityInfo.firstPrice }}</text>
            <text class="original-price">¥{{ activityInfo.price }}</text>
          </view>
          <text class="product-name">{{ productInfo.name }}</text>
          <view class="product-quota">
            <text class="quota-text">该小区仅剩{{ productInfo.quantity }}个购买名额</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 下边框线 -->
    <view class="border-line"></view>

    <!-- 免费安装色块 -->
    <view class="free-install-section">
      <view class="install-badge">
        <image class="install-icon" src="/static/images/product/ico_anzhuang.png" />
        <text class="install-text">免费安装</text>
      </view>
      <view class="quality-badge">
        <image class="quality-icon" src="/static/images/product/ico_zhiliang.png" />
        <text class="quality-text">质量保证</text>
      </view>
      <view class="speed-badge">
        <image class="speed-icon" src="/static/images/product/ico_jisu.png" />
        <text class="speed-text">极速发货</text>
      </view>
    </view>

    <!-- 订单详情 -->
    <view class="order-details">
      <view class="detail-row">
        <text class="detail-label">已选</text>
        <text class="detail-value">壁挂</text>
      </view>
      <view class="detail-row">
        <text class="detail-label">运费</text>
        <text class="detail-value">免运费</text>
      </view>
      <view class="detail-row">
        <text class="detail-label">服务</text>
        <text class="detail-value">专业安装</text>
      </view>
    </view>

    <!-- 商品权益介绍 -->
    <ProductBenefits />
    <view class="benefits-spacer"></view>

    <!-- 购买协议 -->
   

    <!-- 底部间距 -->
    <view class="bottom-spacer"></view>
  </view>

  <!-- 底部确认购买按钮 -->
  <view class="bottom-action">
     <view class="agreement-section">
      <view class="agreement-checkbox" @click="toggleAgreement">
        <checkbox-group @change="onAgreementChange">
          <checkbox 
            :checked="isAgreed" 
            color="#1CCCB4"
          />
        </checkbox-group>
        <text class="agreement-text">我已阅读并同意</text>
        <text class="agreement-link" @click.stop="viewAgreement">《听鸽共享充电桩购买协议》</text>
      </view>
    </view>
    <view 
      class="confirm-button" 
      :class="{ disabled: !isAgreed }"
      @click="confirmPurchase"
    >
      <text class="confirm-text">立即支付</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad as onPageLoad } from '@dcloudio/uni-app'
import ProductBenefits from '@/components/ProductBenefits.vue'
import ActivityApi from '@/api/pile/activity.js'
import PaymentApi from '@/api/pile/payment.js'
import PaymentUtil from '@/utils/payment.js'


const isAgreed = ref(false)
const activityId = ref(null)
const productId = ref(null)
const activityInfo = ref(null)
const productInfo = ref(null)
const plotId = ref(null)
const areaId = ref(null)

const locationInfo = reactive({
  address: '喜民大街家园路万科子山1栋地下A233车位'
})


onPageLoad((options) => {
  console.log('订单确认页面参数:', options)
  
  // 接收activityId和productId参数
  if (options.activityId && options.productId) {
    activityId.value = options.activityId
    productId.value = options.productId
    loadOrderData()
  }
})
const loadOrderData = async () => {
  try {
    // 并行调用两个接口
    const [activityRes, productRes] = await Promise.all([
      ActivityApi.getActivityInfo(activityId.value),
      ActivityApi.getActivityProduct(productId.value)
    ])
    
    // 更新活动信息
    activityInfo.value = activityRes;
    productInfo.value = productRes;


  } catch (error) {
    console.error('加载订单数据失败:', error)
    uni.showToast({
      title: '加载数据失败',
      icon: 'none'
    })
  }
}



const goBack = () => {
  uni.navigateBack()
}

const selectLocation = () => {
  // 跳转到地图选择页面
  uni.navigateTo({
    url: '/pages/activity/map-selection'
  })
}

const onAgreementChange = (e) => {
  isAgreed.value = !isAgreed.value
}

const toggleAgreement = () => {
  isAgreed.value = !isAgreed.value
}

const viewAgreement = () => {
  // 跳转到购买协议页面
  uni.navigateTo({
    url: '/pages/activity/agreement'
  })
}

const confirmPurchase = async () => {
  console.log('confirmPurchase called, isAgreed:', isAgreed.value)
  if (!isAgreed.value) {
    uni.showToast({
      title: '请先同意购买协议',
      icon: 'none'
    })
    return
  }
  
  plotId.value = 1;
  areaId.value = 1;

  try {
    uni.showLoading({
      title: '正在创建订单...'
    });

    // 先调用PaymentApi获取支付参数
    const paymentType = PaymentUtil.getPaymentType();
    const data = await PaymentApi.createPayment(
      activityId.value,
      productId.value,
      plotId.value,
      areaId.value,
      paymentType,
      1
    );

    uni.hideLoading();

    if (!data.success) {
      uni.showToast({
        title: data.errmsg || '创建订单失败',
        icon: 'none'
      });
      return;
    }

    // 使用封装的支付工具
    const callbacks = {
      onSuccess: paymentSuccess,
      onFail: paymentFailed,
      onCancel: () => {
        console.log('用户取消支付');
      }
    };

    await PaymentUtil.initiatePayment(data.payinfo, callbacks);
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error.message || '创建订单失败',
      icon: 'none'
    });
    console.error('创建订单失败:', error);
  }
}

// 原有的wechatPay函数已被PaymentUtil.initiatePayment替代

const paymentSuccess = (payRes) => {
  console.log('支付成功回调:', payRes);
  // 支付成功后跳转到shared-pile/index页面，携带状态=1
  setTimeout(() => {
    uni.redirectTo({
      url: '/pages/activity/shared-pile/index?pileStatus=1'
    })
  }, 1000)
}

const paymentFailed = (error) => {
  console.log('支付失败回调:', error);
  // 可以在这里添加支付失败后的额外处理逻辑
  // 例如：记录失败日志、显示重试按钮等
}
</script>

<style scoped>
.order-confirm-page {
  /* background-color: #f5f5f5; */
  min-height: 100vh;
}

/* 边框线 */
.border-line {
  height: 1px;
  background-color: #f0f0f0;
  margin: 0 20px;
}

/* 顶部导航 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
}

.header-left {
  width: 60px;
}

.back-icon {
  width: 24px;
  height: 24px;
}

.header-title {
  font-size: 18px;
  font-weight: 500;
  color: #333333;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
  width: 60px;
  justify-content: flex-end;
}

.more-icon,
.share-icon {
  width: 24px;
  height: 24px;
}

/* 安装地点选择 */
.location-section {
  background-color: #ffffff;
  margin-top: 10px;
  padding: 20px;
}

.location-header {
  margin-bottom: 15px;
}

.location-label {
  font-weight: 400;
  font-size: 28rpx;
  color: #7A7A7C;
  line-height: 40rpx;
}

.location-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.location-address {
  font-weight: 400;
  font-size: 40rpx;
  color: #000000;
  line-height: 56rpx;
  flex: 1;
}

.location-edit {
  width: 20px;
  height: 20px;
}

/* 商品信息 */
.product-section {
  background-color: #ffffff;
  margin-top: 10px;
  padding: 20px;
  /* border-top: 1px solid #f0f0f0; */
  /* border-bottom: 1px solid #f0f0f0; */
}

.product-info {
  display: flex;
  gap: 15px;
}

.product-image {
  width: 240rpx;
  height: 240rpx;
  border-radius: 16rpx;
}

.product-details {
  flex: 1;
}

.product-price {
  display: flex;
  align-items: baseline;
  gap: 16rpx;
  margin-bottom: 16rpx;
}

.current-price {
  font-size: 72rpx;
  color: #FF5A17;
  line-height: 100rpx;
}

.original-price {
  font-size: 28rpx;
  color: #7A7A7C;
  line-height: 40rpx;
  text-decoration: line-through;
}

.product-name {
  font-weight: 500;
  font-size: 40rpx;
  color: #000000;
  line-height: 56rpx;
  margin-bottom: 16rpx;
}

.product-quota {
  background: linear-gradient(270deg, #FFFCE4 0%, #FFDCC9 100%);
  border-radius: 12px;
  padding: 8px 12px;
  margin-top: 8px;
}

.quota-text {
  font-size: 12px;
  color: #ff6b35;
  font-weight: 500;
}

/* 免费安装色块样式 */
.free-install-section {
  background: linear-gradient(310deg, #61EDDA 0%, #FFFFC0 100%);
  border-radius: 8px;
  margin: 10px 20px;
  padding: 10px 18px 10px 18px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.install-badge,
.quality-badge,
.speed-badge {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 6px;
}

.install-icon,
.quality-icon {
  width: 24px;
  height: 24px;
}

.speed-icon {
  width: 24px;
  height: 29px;
}

.install-text,
.quality-text,
.speed-text {
  font-size: 15px;
  color: #333333;
  font-weight: 500;
}

/* 订单详情 */
.order-details {
  background-color: #ffffff;
  margin-top: 10px;
  padding: 0px 20px 0px 20px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-row:last-child {
  border-bottom: none;
}

.detail-label {
  font-size: 14px;
  color: #666666;
}

.detail-value {
  font-size: 14px;
  color: #333333;
}



/* 商品权益底部间距 */
.benefits-spacer {
  margin-bottom: 140rpx;
}

/* 购买协议 */
.agreement-section {
  background-color: #ffffff;
  /* margin-top: 10px; */
  padding: 0px 0 20px 0;
}



/* uni-data-checkbox 样式 */
.agreement-checkbox {
  display: flex;
  align-items: center;
  /* gap: 8px; */
}

.agreement-checkbox checkbox {
  transform: scale(0.8);
}

.agreement-text {
  font-size: 16px;
  color: #666666;
}

.agreement-link {
  font-size: 16px;
  color: #1CCCB4;
}

/* 底部间距 */
.bottom-spacer {
  height: 80px;
}

/* 底部确认购买按钮 */
.bottom-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
}

.confirm-button {
  background-color: #00d4aa;
  border-radius: 25px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.confirm-button.disabled {
  background-color: #cccccc;
}

.confirm-text {
  font-size: 16px;
  font-weight: 500;
  color: #ffffff;
}
</style>